'use client';

import { useState, useCallback } from 'react';
import { Copy, Check, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

interface CopyButtonProps {
  text: string;
  className?: string;
  size?: 'default' | 'sm' | 'lg' | 'icon';
  variant?: 'default' | 'ghost' | 'outline';
  showToast?: boolean;
  toastMessage?: string;
  children?: React.ReactNode;
}

/**
 * 复制按钮组件
 * 提供一键复制功能，支持多种样式和反馈方式
 */
export function CopyButton({
  text,
  className,
  size = 'sm',
  variant = 'ghost',
  showToast = true,
  toastMessage = '已复制到剪贴板',
  children,
}: CopyButtonProps) {
  const [copied, setCopied] = useState(false);
  const [error, setError] = useState(false);

  /**
   * 复制文本到剪贴板
   */
  const copyToClipboard = useCallback(async () => {
    try {
      // 优先使用现代 Clipboard API
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(text);
      } else {
        // 降级到传统方法
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        const successful = document.execCommand('copy');
        document.body.removeChild(textArea);

        if (!successful) {
          throw new Error('复制失败');
        }
      }

      setCopied(true);
      setError(false);

      if (showToast) {
        toast.success(toastMessage);
      }

      // 2秒后重置状态
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error('复制失败:', err);
      setError(true);
      setCopied(false);

      if (showToast) {
        toast.error('复制失败，请手动复制');
      }

      // 3秒后重置错误状态
      setTimeout(() => setError(false), 3000);
    }
  }, [text, showToast, toastMessage]);

  const getIcon = () => {
    if (error) return <AlertCircle className="h-4 w-4 text-red-500" />;
    if (copied) return <Check className="h-4 w-4 text-green-500" />;
    return <Copy className="h-4 w-4" />;
  };

  const getTitle = () => {
    if (error) return '复制失败';
    if (copied) return '已复制';
    return '复制';
  };

  return (
    <Button
      variant={variant}
      size={size}
      onClick={copyToClipboard}
      className={cn(
        'transition-all duration-200',
        copied &&
          'bg-green-50 hover:bg-green-100 dark:bg-green-950 dark:hover:bg-green-900',
        error &&
          'bg-red-50 hover:bg-red-100 dark:bg-red-950 dark:hover:bg-red-900',
        className
      )}
      title={getTitle()}
      disabled={copied}
    >
      {getIcon()}
      {children && <span className="ml-2">{children}</span>}
    </Button>
  );
}

/**
 * 内联复制组件
 * 用于在文本旁边显示复制按钮
 */
interface InlineCopyProps {
  text: string;
  displayText?: string;
  className?: string;
  showIcon?: boolean;
}

export function InlineCopy({
  text,
  displayText,
  className,
  showIcon = true,
}: InlineCopyProps) {
  const [copied, setCopied] = useState(false);

  const copyToClipboard = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      toast.success('已复制到剪贴板');
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error('复制失败:', err);
      toast.error('复制失败');
    }
  }, [text]);

  return (
    <span className={cn('inline-flex items-center gap-1 group', className)}>
      <code className="px-2 py-1 bg-gray-100 dark:bg-gray-800 rounded text-sm font-mono">
        {displayText || text}
      </code>
      {showIcon && (
        <button
          onClick={copyToClipboard}
          className="opacity-0 group-hover:opacity-100 transition-opacity p-1 hover:bg-gray-100 dark:hover:bg-gray-800 rounded"
          title="复制"
        >
          {copied ? (
            <Check className="h-3 w-3 text-green-500" />
          ) : (
            <Copy className="h-3 w-3 text-gray-500" />
          )}
        </button>
      )}
    </span>
  );
}

/**
 * 代码块复制包装器
 * 为代码块添加悬浮复制按钮
 */
interface CodeCopyWrapperProps {
  code: string;
  children: React.ReactNode;
  className?: string;
  position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left';
}

export function CodeCopyWrapper({
  code,
  children,
  className,
  position = 'top-right',
}: CodeCopyWrapperProps) {
  const positionClasses = {
    'top-right': 'top-2 right-2',
    'top-left': 'top-2 left-2',
    'bottom-right': 'bottom-2 right-2',
    'bottom-left': 'bottom-2 left-2',
  };

  return (
    <div className={cn('relative group', className)}>
      {children}
      <div
        className={cn(
          'absolute opacity-0 group-hover:opacity-100 transition-opacity duration-200 z-10',
          positionClasses[position]
        )}
      >
        <CopyButton
          text={code}
          size="sm"
          variant="outline"
          className="bg-white dark:bg-gray-900 border shadow-sm"
        />
      </div>
    </div>
  );
}

/**
 * 批量复制功能
 * 支持复制多个文本片段
 */
interface BatchCopyProps {
  items: Array<{
    label: string;
    text: string;
  }>;
  className?: string;
}

export function BatchCopy({ items, className }: BatchCopyProps) {
  const [copiedIndex, setCopiedIndex] = useState<number | null>(null);

  const copyItem = useCallback(async (text: string, index: number) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedIndex(index);
      toast.success('已复制到剪贴板');
      setTimeout(() => setCopiedIndex(null), 2000);
    } catch (err) {
      console.error('复制失败:', err);
      toast.error('复制失败');
    }
  }, []);

  const copyAll = useCallback(async () => {
    try {
      const allText = items
        .map(item => `${item.label}: ${item.text}`)
        .join('\n');
      await navigator.clipboard.writeText(allText);
      toast.success('已复制所有内容');
    } catch (err) {
      console.error('复制失败:', err);
      toast.error('复制失败');
    }
  }, [items]);

  return (
    <div className={cn('space-y-2', className)}>
      <div className="flex justify-between items-center">
        <h4 className="text-sm font-medium text-gray-900 dark:text-gray-100">
          复制选项
        </h4>
        <Button
          variant="outline"
          size="sm"
          onClick={copyAll}
          className="text-xs"
        >
          <Copy className="h-3 w-3 mr-1" />
          全部复制
        </Button>
      </div>

      <div className="space-y-1">
        {items.map((item, index) => (
          <div
            key={index}
            className="flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-800 rounded"
          >
            <div className="flex-1 min-w-0">
              <div className="text-xs font-medium text-gray-600 dark:text-gray-400">
                {item.label}
              </div>
              <div className="text-sm font-mono text-gray-900 dark:text-gray-100 truncate">
                {item.text}
              </div>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => copyItem(item.text, index)}
              className="ml-2 h-8 w-8 p-0"
            >
              {copiedIndex === index ? (
                <Check className="h-3 w-3 text-green-500" />
              ) : (
                <Copy className="h-3 w-3" />
              )}
            </Button>
          </div>
        ))}
      </div>
    </div>
  );
}
